package com.maoning.gulimallcart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.maoning.common.utils.R;
import com.maoning.gulimallcart.feign.ProductFeignService;
import com.maoning.gulimallcart.interceptor.CartInterceptor;
import com.maoning.gulimallcart.service.CartService;
import com.maoning.gulimallcart.to.UserInfoTo;
import com.maoning.gulimallcart.vo.Cart;
import com.maoning.gulimallcart.vo.CartItem;
import com.maoning.gulimallcart.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Locale;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author : 猫宁
 * @Date: 2022/4/5
 */
@Slf4j
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private ThreadPoolExecutor executor;

    private final static String CART_PREFIX = "gulimall:cart:";


    @Override
    public CartItem addToCart(Long skuId, Integer num) {
        final BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        final String ops = (String) cartOps.get(skuId.toString());
        CartItem cartItem = new CartItem();
        if(StringUtils.isEmpty(ops)){
            //新商品,直接添加
            addNewItem(skuId, num, cartOps, cartItem);
        }else {
            //购物车已有的商品,直接加数量
            cartItem = JSONObject.parseObject(ops, CartItem.class);
            cartItem.setCout(cartItem.getCout() + num);
            final String cartItemJson = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(), cartItemJson);
        }
        return cartItem;
    }

    @Override
    public CartItem getCartItem(String skuId) {
        final BoundHashOperations<String, Object, Object> ops = getCartOps();
        final String data = (String) ops.get(skuId.toString());
        final CartItem cartItem = JSON.parseObject(data, CartItem.class);
        return cartItem;


    }


    private void addNewItem(Long skuId, Integer num, BoundHashOperations<String, Object, Object> cartOps, CartItem cartItem) {
        final CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
            //1.根据skuId远程查

            final R info = productFeignService.info(skuId);
            if (info.getCode() == 0) {
                final SkuInfoVo skuInfo = info.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                //2.操作redis新增

                cartItem.setCout(num);
                cartItem.setSkuId(skuId);
                cartItem.setCheck(true);
                cartItem.setImage(skuInfo.getSkuDefaultImg());
                cartItem.setPrice(skuInfo.getPrice());
                cartItem.setTitle(skuInfo.getSkuTitle());
            }
        }, executor);
        final CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> {
            final List<String> stringList = productFeignService.getSkuSaleAttrValuesBySkuId(skuId);
            if (!CollectionUtils.isEmpty(stringList)) {
                cartItem.setSkuAttr(stringList);
            }
        }, executor);
        try {
            CompletableFuture.allOf(future1,future2).get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        final String cartItemJson = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(), cartItemJson);
    }

    /**
     * 获取到要操作的redis绑定购物车
     * 会根据临时用户或者登陆登陆拿对应的
     * redis的hash的绑定操作,ops的绑定操作
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        final UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey;
        if(userInfoTo.getUserId() != null){
            //登陆用户的购物车
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        }else {
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        BoundHashOperations<String, Object, Object> boundHashOps = redisTemplate.boundHashOps(cartKey);
        return boundHashOps;
    }
}
